package day03;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/2/26 15:25
 * 重复则-找最左边的 Leftmost
 */
public class BinarySearchLeft {
    public static void main(String[] args) {
        int[] arr = { 1, 2, 3, 3, 4, 6, 10, 11 };
        int index = binarySearchLeftmost(arr, 3);
        System.out.println(index);
    }
    public static int binarySearchLeftmost(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;
        int candidate = -1;
        while (low <= high) {
            int mid = (low + high) >>> 1;
            if (target < arr[mid]) {
                high = mid - 1;
            } else if (arr[mid] < target) {
                low = mid + 1;
            } else {
                // return mid;

                // 将侯选位置记录
                candidate = mid;
                // 缩小边界,不断往左找
                high = mid - 1;
            }
        }
        return candidate;
    }
}
